from logging import warning

from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver


class BasePage:

    def __init__(self, web_driver):
        self._web_driver = web_driver
        self.__set_web_element()

    def __set_web_element(self):
        for locator in self.locators:
            try:
                web_element = self.web_driver.find_element(*self.locators.get(locator))
            except NoSuchElementException as exc:
                warning(exc)
                web_element = None
            setattr(type(self), locator.rstrip("_loc"), web_element)

    @property
    def locators(self):
        dict_ = getattr(type(self), "__dict__")
        locators_dict = {k: dict_[k] for k in dict_
                         if k.endswith("_loc") and isinstance(dict_[k], tuple)}
        # 将符合以_loc结尾的元组作为定位器加入locators
        return locators_dict

    @property
    def web_driver(self):
        assert isinstance(self._web_driver, WebDriver)
        return self._web_driver


if __name__ == '__main__':
    # test
    class LoginPage(BasePage):
        username_loc = (By.ID, "u")
        password_loc = (By.ID, "p")

        def login(self, username, password):
            pass


    c = Chrome()
    c.get("file:///../test/testpage.html")
    try:
        l = LoginPage(c)
        print(l.locators)
        print(l.username)
        print(l.password)
    except Exception as e:
        print("=======")
        print(e)
    finally:
        c.quit()
